package javabase.concurrent;

import tools.RequestIdGenerator;

public class RaceConditionDemo {

    static class WorkThread extends Thread {
        private final int requestCount;

        public WorkThread(int id, int requestCount) {
            super("work-" + id);
            this.requestCount = requestCount;
        }

        @Override
        public void run() {
            int i = requestCount;
            while (i-- > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.printf("%s got requestId: %s", Thread.currentThread().getName(), RequestIdGenerator.getInstance().nextId());
                System.out.println();
            }
        }
    }

    public static void main(String[] args) {
        int numberOfThreads = Runtime.getRuntime().availableProcessors();
        Thread[] workerThreads = new Thread[numberOfThreads];
        for (int i=0; i<numberOfThreads; i++) {
            workerThreads[i] = new WorkThread(i, 10);
        }
        for (Thread t : workerThreads) {
            t.start();
        }
    }


}
